package com.gxa.login.service.impl;

import com.gxa.login.dao.MemberDao;
import com.gxa.login.service.ForgetPwdService;
import com.gxa.login.validator.MyValidator;
import dto.ResultDTO;
import entity.Member;
import group.ForgetPwd;
import group.Send;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import param.ForgetParam;
import param.MailDTO;
import util.Response;

import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Service
public class ForgetPwdServiceImpl implements ForgetPwdService {

    @Autowired
    private MyValidator myValidator;

    @Resource
    private MemberDao memberDao;

    @Resource(name = "objectRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public ResultDTO forgetPwd(ForgetParam forgetParam) {
        myValidator.validate(forgetParam, ForgetPwd.class);
        if(!redisTemplate.hasKey("emailCode:"+forgetParam.getEmail())){
            return Response.error(1001,"验证码已过期");
        }
        Object pop = redisTemplate.opsForSet().pop("emailCode:" + forgetParam.getEmail());
        if(!pop.equals(forgetParam.getCode())){
            return Response.error(1002,"验证码不正确");
        }
        Member member = new Member();
        member.setMemberPwd(forgetParam.getNewPwd());
        member.setMemberEmail(member.getMemberEmail());
        int update = memberDao.update(member);
        if(update == 0){
            return Response.error(1001,"修改失败");
        }
        return Response.success(200,"修改成功");
    }

    @Override
    public ResultDTO sendEmail(ForgetParam forgetParam) {
        myValidator.validate(forgetParam, Send.class);
        if (!redisTemplate.hasKey("is:email")) {
            MailDTO mailDTO = new MailDTO();
            mailDTO.setSubject("忘记密码");
            String[] str = new String[1];
            str[0] = forgetParam.getEmail();
            mailDTO.setTo(str);
            String[] str1 = new String[1];
            str1[0] = "377576540@qq.com";
            mailDTO.setCc(str1);
            mailDTO.setText("");
            // 发消息
            rocketMQTemplate.convertAndSend("email-code", mailDTO);
            //设置时间
            redisTemplate.opsForSet().add("is:email", "1");
            redisTemplate.expire("is:email", 60, TimeUnit.SECONDS);
            return Response.success(200, "发送成功");
        }
    return Response.success(200, "发送邮件频繁");

    }


}
